import 'dart:async';

import 'package:star_author/config/app.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:star_author/utils/statistics/event/backflow_event.dart';
import 'package:star_author/utils/statistics/huiliu/event.dart';
import 'package:star_author/utils/statistics/huiliu/huiliu_statistics.dart';
import 'package:star_author/utils/statistics/statistics.dart';

import '../../../config/base_configuration.dart';
import '../../../provider/user.dart';
import '../../../utils/common_util/log_util.dart';
import '../../../utils/common_util/num_util.dart';
import '../../../utils/common_util/shared_preferences/sp_keys_constant.dart';
import '../../../utils/common_util/shared_preferences/sp_util.dart';
import '../../../utils/config_provider_util.dart';
import '../../../utils/http/api_manager.dart';
import '../../../utils/http/http_util.dart';
import '../../../utils/number.dart';
import '../../../utils/rouces_util.dart';
import '../../../utils/toast_util.dart';
import '../../../utils/utils.dart';
import '../../../widgets/button_widget.dart';
import '../../../widgets/dialog/dialog_type.dart';
import '../../../widgets/dialog/get_dialog.dart';
import '../../../widgets/dialog/sure_dialog.dart';
import '../../../widgets/image_widget.dart';

class TenderFormDialogUtil {
  static show(
    id,
    Function callBack,
    Map param, {
    OfferForm offerForm: OfferForm.detail,
    double previous_max_tender_price: 0,
    price_range: const [],
    Function? nextCall,
  }) {
    Get.bottomSheet(
      TenderFormDialog(
        backflowId: id,
        previous_max_tender_price: previous_max_tender_price,
        price_range: price_range,
        param: param,
      ),
      isScrollControlled: true,
    ).then((value) {
      if (nextCall != null) {
        nextCall();
      }
      if (value == "ok") {
        callBack();
      }
    });
  }
}

enum OfferForm {
  detail,
  live,
}

class TenderFormDialog extends StatefulWidget {
  int backflowId = 0;
  OfferForm offerForm;
  double previous_max_tender_price = 0;
  List? price_range;
  Map param;
  TenderFormDialog({
    Key? key,
    this.backflowId: 0,
    this.offerForm: OfferForm.detail,
    this.previous_max_tender_price: 0,
    this.price_range: const [],
    required this.param,
  }) : super(key: key);

  @override
  State<TenderFormDialog> createState() => _TenderFormDialogState();
}

class _TenderFormDialogState extends State<TenderFormDialog>
    with WidgetsBindingObserver {
  late FToast fToast;

  double available_guarantee = 0.0; //保证金余额

  double tender_price = 0.0; //最高可出价金额,保证金余额* max_deductible_amount

  //当前出价金额
  double current_price = 0;

  bool get isLive {
    return widget.offerForm == OfferForm.live;
  }

  bool isLoading = true; //添加一个loading 防止进入页面就输入出现卡位数字

  final TextEditingController _priceController = TextEditingController();

  void fetchBackflow() {
    if (widget.offerForm == OfferForm.detail) {
      StatisticsUtil.event(BiddingEvent.offer, getUMengMap({}));
    }
    isAgree = SpUtil.getBool(SpKeysConstant.offerPrice) ?? false;

    HuiLiuStatistics().event(HuiLiuEvent.click_button_for_applying_tender, {
      'id': widget.backflowId,
    });
    current_price = double.parse((widget.param['tender_price'] ?? "0"));
    tender_price =
        available_guarantee * ConfigProviderUtil.available_bid_multiple;
  }

  //追加保证金后返回刷新用户数据
  initGuaranteePrice() async {
    await HttpUtil.commonRequest(
      Get.context!,
      ApiManager.current_tiny,
      isLoading: false,
    ).then(
      (value) async {
        available_guarantee =
            double.tryParse(value.data['available_guarantee'] ?? "0") ?? 0;
        initPrice();
        if (mounted) setState(() {});
      },
    );
  }

  initPrice() {
    //是否加价
    bool isAppend = current_price > 0;
    if (isAppend) {
      //本次出价 后台扣除的保证金 没有膨胀的
      double deducted = NumUtil.divide(
          current_price, ConfigProviderUtil.available_bid_multiple);
      LogUtil.v("deducted:$deducted");
      LogUtil.v("available_guarantee:$available_guarantee");
      //计算出膨胀后的保证金+保证金余额
      available_guarantee = NumUtil.add(deducted, available_guarantee);
      LogUtil.v('available_guarantee:$available_guarantee');
    }

    tender_price =
        available_guarantee * ConfigProviderUtil.available_bid_multiple;
    LogUtil.v("保证金余额:$available_guarantee 可出价额度:$tender_price");
  }

  Timer? timer = null;

  RxInt count = App.popover_wait_time.obs;

  RxBool canSubmit = false.obs;

  void showTips(BuildContext context) {
    count = App.popover_wait_time.obs;
    canSubmit = false.obs;
    if (timer != null) {
      if (timer?.isActive ?? false) {
        timer?.cancel();
      }
    }

    if (count > 0) {
      timer = Timer.periodic(Duration(seconds: 1), (_) {
        if (count.value == 1) {
          canSubmit.value = true;
          _.cancel();
          timer?.cancel();
        } else {
          count--;
        }
      });
    } else {
      canSubmit.value = true;
    }

    showGetDialog(
      StatefulBuilder(
        builder: (context, setState2) {
          return Column(
            children: [
              Container(
                child: Text(
                  '确认提交出价？',
                  style: TextStyle(
                    fontSize: 18.sp,
                    color: rgba(51, 51, 51, 1),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                margin: EdgeInsets.only(
                  bottom: 20.w,
                  top: 24.w,
                ),
              ),
              Container(
                child: Text(
                  '¥${getMoneyStyleStr(double.parse(_priceController.text).toInt().toString())}',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: rgba(224, 32, 32, 1),
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              SizedBox(
                height: 10.w,
              ),
              Text.rich(
                TextSpan(
                  text: '提交出价后不可撤销',
                ),
                style: TextStyle(
                  fontSize: 14.sp,
                  color: rgba(153, 153, 153, 1),
                ),
                textAlign: TextAlign.center,
              ),
              Container(
                margin: EdgeInsets.only(top: 24.0.w),
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(color: ColorConf.darkWhite),
                  ),
                ),
                height: 43.w,
                padding: EdgeInsets.only(bottom: 0),
                child: Flex(
                  direction: Axis.horizontal,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      flex: 1,
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          primary: ColorConf.yellow,
                          fixedSize: Size.fromHeight(43.w),
                          side: BorderSide(style: BorderStyle.none),
                          shape: const RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(
                              Radius.circular(0),
                            ),
                          ),
                        ),
                        onPressed: () {
                          timer?.cancel();
                          Navigator.pop(context, 'Cancel');
                        },
                        child: Text(
                          "取消",
                          style: TextStyle(
                            color: ColorConf.lightGray,
                            fontSize: 16.sp,
                            decoration: TextDecoration.none,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    ),
                    Container(
                      width: 1.w,
                      height: 43.w,
                      color: ColorConf.darkWhite,
                    ),
                    Expanded(
                      flex: 1,
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          primary: ColorConf.yellow,
                          fixedSize: Size.fromHeight(43.w),
                          side: BorderSide(style: BorderStyle.none),
                          shape: const RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(
                              Radius.circular(0),
                            ),
                          ),
                        ),
                        onPressed: () {
                          if (canSubmit.value) {
                            Navigator.pop(context);
                            FocusScope.of(context).unfocus();
                            double price =
                                double.tryParse(_priceController.text) ?? 0;
                            if (price <
                                (widget.param['bid_notice_amount'] ?? 100)) {
                              LogUtil.v("小于100 直接出价");
                              submitTender();
                            } else {
                              //判断是否高于市场价
                              if ((widget.param['is_overbid_alert'] ?? false)) {
                                double alertMultiple = double.tryParse(
                                        widget.param['alert_multiple'] ??
                                            "0") ??
                                    0;

                                if (widget.price_range!.length > 0) {
                                  var max = widget.price_range!.reduce((value,
                                          element) =>
                                      ((double.tryParse(value ?? "0")) ?? 0) >
                                              ((double.tryParse(
                                                      element ?? "0")) ??
                                                  0)
                                          ? value
                                          : element);
                                  double maxD = double.tryParse(max) ?? 0;
                                  if (price >=
                                          NumUtil.multiply(
                                              alertMultiple, maxD) &&
                                      maxD != 0) {
                                    DialogUtil.showMyDialog(
                                      dialogType:
                                          DialogType.money_to_height_tips,
                                      param: {
                                        "money": _priceController.text,
                                      },
                                      leftButtonOnTap: () {
                                        submitTender();
                                      },
                                      rightButtonOnTap: () {
                                        focusNode.requestFocus();
                                      },
                                    );
                                  } else {
                                    submitTender();
                                  }
                                } else {
                                  submitTender();
                                }
                              } else {
                                submitTender();
                              }
                            }
                          }
                        },
                        child: Obx(
                          () => Text(
                            "${canSubmit.value ? "确定" : "$count" + "s"}",
                            style: TextStyle(
                              color: ColorConf.yellow,
                              fontSize: 16.sp,
                              decoration: TextDecoration.none,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )
            ],
          );
        },
      ),
      barrierDismissible: false,
    );
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

  void update() {
    if (mounted) setState(() {});
  }

  List money_formats = [
    '个',
    '十',
    '百',
    '千',
    '万',
    '十万',
    '百万',
    '千万',
    '亿',
  ];

  String money_tips = "";

  @override
  void initState() {
    super.initState();
    fToast = FToast();
    fToast.init(context);
    // 必须添加观察者监听
    WidgetsBinding.instance?.addObserver(this);
    fetchBackflow();
    initGuaranteePrice();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        LogUtil.v("页面状态前台:$state");
        initGuaranteePrice();
        break;
      case AppLifecycleState.paused:
        LogUtil.v("页面状态后台:$state");
        break;
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

  String firstTips = '如果您的出价不足最高出价的30%，则会被判定为无效出价；出价提交后只可加价，中拍后不可悔标、不可退货。';

  void showCustomToast(String title, String image) {
    Widget toast = Container(
      padding: EdgeInsets.symmetric(
        horizontal: 20.w,
        vertical: 18.w,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.w),
        color: Colors.black.withOpacity(0.5),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            image,
            width: 30.w,
            height: 30.w,
          ),
          SizedBox(
            width: 10.w,
          ),
          Text(
            title,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );

    fToast.showToast(
      child: toast,
      gravity: ToastGravity.CENTER,
      toastDuration: Duration(seconds: 3),
    );
  }

  void submitTender() async {
    String price = _priceController.text.toString();
    int id = widget.backflowId;
    if (isLive) {
      StatisticsUtil.event(
        BiddingLiveEvent.submit_offer_dialog_sure,
        getUMengMap(
          {
            "submit_price": price,
            "backflow_id": id.toString(),
          },
        ),
      );
    } else {
      StatisticsUtil.event(
        BiddingEvent.submit_offer_dialog_sure,
        getUMengMap(
          {
            "submit_price": price,
            "backflow_id": id.toString(),
          },
        ),
      );
    }
    HttpUtil.commonRequest(
      Get.context!,
      ApiManager.tenders,
      isErrorToast: false,
      data: {
        'backflow_id': id,
        'price': price,
        "is_raise_price": current_price > 0,
      },
      method: HttpUtil.MethodPost,
    ).then(
      (response) {
        if (response.statusCode == 201) {
          if (isLive) {
            StatisticsUtil.event(
              BiddingLiveEvent.submit_success,
              getUMengMap(
                {
                  "price": price,
                  'backflow_id': id.toString(),
                },
              ),
            );
          } else {
            StatisticsUtil.event(
              BiddingEvent.submit_success,
              getUMengMap(
                {
                  "price": price,
                  'backflow_id': id.toString(),
                },
              ),
            );
          }
          if (current_price > 0) {
            StatisticsUtil.event(SystemEvent.jia_jia_ti_jiao_cheng_gong, {
              "backflow_id": id.toString(),
            });
          }
          HuiLiuStatistics().event(HuiLiuEvent.apply_tender_for_backflow, {
            'id': widget.backflowId,
          });
          showCustomToast("出价成功", "images/ic_offer_successful_lt.png");
          Get.back(result: 'ok');
        } else {
          showCustomToast("出价失败", "images/ic_offer_failure_lt.png");
        }
      },
    ).catchError(
      (e) {
        LogUtil.v(e.response?.statusCode);
        DioError dioError = e as DioError;
        if (dioError.response?.statusCode == 422) {
          showCustomToast(dioError.response?.data['msg'] ?? "当前竞拍结束",
              "images/ic_offer_failure_lt.png");
        } else {
          showCustomToast("出价失败", "images/ic_offer_failure_lt.png");
        }
      },
    );
  }

  int get minimumEvaluationLength {
    return 1;
  }

  get user {
    var userModel = Provider.of<UserProvider>(context, listen: false);
    return userModel.user;
  }

  bool visible = false;
  String visibleStr = "";

  onChanged(String val) {
    int number = int.tryParse(val) ?? 0;
    if (val.isNotEmpty) {
      if (number > 0) {
        if (user['is_vip']) {
          //白名单不限制
          visible = false;
        } else if (available_guarantee <
                ConfigProviderUtil.max_deductible_amount &&
            int.parse(val.toString()) > tender_price) {
          visibleStr = '当前出价超过剩余可出价金额';
          visible = true;
        } else {
          visible = false;
        }
      } else {
        visibleStr = '出价金额不能为空';
        visible = true;
      }
      double money = double.tryParse(_priceController.text) ?? 0;
      if (money >= 100) {
        setState(() {
          money_tips = money_formats[money.toInt().toString().length - 1];
        });
      } else {
        setState(() {
          money_tips = "";
        });
      }
      if (current_price > 0) {
        if (number <= current_price) {
          visibleStr = '重新出价必须高于当前已出价';
          visible = true;
        }
      }
    } else {
      visibleStr = '出价金额不能为空';
      visible = true;
    }

    LogUtil.v("visibleStr:$visibleStr");
    LogUtil.v("visible:$visible");
    update();
  }

  bool isAgree = false;

  setAgree() {
    SpUtil.putBool(SpKeysConstant.offerPrice, true);
  }

  Widget buildCheckItem() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: Container(
            width: 15.w,
            height: 15.w,
            margin: EdgeInsets.only(right: 10.w),
            child: Center(
              child: Icon(
                Icons.check_outlined,
                color: isAgree ? Color(0xFFFEBA07) : Colors.transparent,
                size: 11.w,
              ),
            ),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2),
                border: Border.all(
                    width: 1.w,
                    color: isAgree ? Color(0xFFFEBA07) : Color(0xFF999999))),
          ),
          onTap: () {
            setState(() {
              if (!isAgree) {
                setAgree();
              }
              isAgree = !isAgree;
            });
          },
        ),
        Text(
          "我已经阅读并同意",
          style: TextStyle(fontSize: 12.sp, color: Color(0xFF999999)),
        ),
        InkWell(
          child: Text(
            "《回流买家须知》",
            style: TextStyle(fontSize: 12.sp, color: Color(0xFF037AFF)),
          ),
          onTap: () {},
        )
      ],
    );
  }

  buildPriceRange({double top: 20}) {
    if ((widget.price_range ?? []).length > 0) {
      return Container(
        margin: EdgeInsets.only(
          top: top.w,
        ),
        child: Text(
          "源头市场价 ${getPriceWithList(
            widget.price_range ?? [],
            show_name: widget.param['price_range_show_name'] ?? "",
            intl: true,
          )}",
          style: TextStyle(
            fontSize: 14.sp,
            color: rgba(255, 143, 0, 1),
          ),
        ),
        alignment: Alignment.centerLeft,
      );
    }
    return Container();
  }

  FocusNode focusNode = FocusNode();

  Widget buildContent() {
    if (current_price > 0) {
      return Container(
        margin: EdgeInsets.only(
          top: 10.w,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              child: Row(
                children: [
                  ImageWithPlaceHolder(
                    width: 68.w,
                    height: 68.w,
                    cover: widget.param['goods']['cover']['url'] ?? "",
                    radius: 2.w,
                  ),
                  SizedBox(
                    width: 10.w,
                  ),
                  Container(
                    height: 68.w,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Text(
                          '当前出价¥${getMoneyStyleStr(current_price.toInt().toString())}',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: rgba(255, 143, 0, 1),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        Text(
                          '重新出价必须高于当前已出价',
                          style: TextStyle(
                            color: rgba(153, 153, 153, 1),
                            fontSize: 12.sp,
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
              margin: EdgeInsets.only(
                bottom: 10.w,
                top: 10.w,
              ),
            ),
            Container(
              height: 68.w,
              width: Get.width - 24.w,
              decoration: BoxDecoration(
                color: rgba(246, 246, 246, 1),
                borderRadius: BorderRadius.circular(4.w),
              ),
              child: Container(
                decoration: BoxDecoration(
                  color: rgba(246, 246, 246, 1),
                  borderRadius: BorderRadius.circular(2.w),
                ),
                height: 68.w,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(
                  left: 20.w,
                ),
                child: Stack(
                  alignment: Alignment.centerLeft,
                  children: [
                    TextFormField(
                      onChanged: (v) {
                        onChanged(v);
                      },
                      controller: _priceController,
                      focusNode: focusNode,
                      cursorColor: ColorConf.yellow,
                      textAlignVertical: TextAlignVertical.center,
                      keyboardType: TextInputType.number,
                      showCursor: true,
                      autofocus: true,
                      //显示光标
                      // readOnly: true, // 禁用唤起系统键盘
                      inputFormatters: [
                        XNumberTextInputFormatter(
                          isAllowDecimal: false,
                          maxIntegerLength: 9,
                        ),
                      ],
                      style: TextStyle(
                        fontSize: 18.sp,
                        color: ColorConf.black,
                        fontWeight: FontWeight.w500,
                      ),
                      decoration: InputDecoration(
                        suffixIcon: _priceController.text.isEmpty
                            ? null
                            : IconButton(
                                onPressed: () {
                                  _priceController.clear();
                                  onChanged(_priceController.text);
                                },
                                icon: Image(
                                  image: AssetImage(
                                      "images/lt_user/circle_clear.png"),
                                  width: 16.w,
                                  height: 16.w,
                                )),
                        prefixIcon: Container(
                          padding: EdgeInsets.symmetric(horizontal: 5.0.w),
                          child: Text(
                            '¥',
                            style: TextStyle(
                              color: ColorConf.black,
                              fontSize: 18.sp,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                        contentPadding: EdgeInsets.zero,
                        prefixIconConstraints: BoxConstraints(
                          maxHeight: 68.w,
                        ),
                        hintText: "请输入新的出价金额 ",
                        labelStyle: new TextStyle(
                          color: const Color(0xFFCCCCCC),
                        ),
                        isCollapsed: true,
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                          color: ColorConf.highlightGray,
                          fontSize: 16.sp,
                        ),
                      ),
                    ),
                    if ((double.tryParse(_priceController.text) ?? 0) >= 100)
                      Positioned(
                        left: (20.w + _priceController.text.length * 14.sp),
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 4.w,
                            vertical: 2.w,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            money_tips,
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: rgba(102, 102, 102, 1),
                            ),
                          ),
                        ),
                      )
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        buildPriceRange(),
        Container(
          margin: EdgeInsets.only(
            top: 10.w,
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ImageWithPlaceHolder(
                width: 68.w,
                height: 68.w,
                cover: widget.param['goods']['cover']['url'] ?? "",
              ),
              SizedBox(
                width: 10.w,
              ),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: rgba(246, 246, 246, 1),
                    borderRadius: BorderRadius.circular(2.w),
                  ),
                  height: 68.w,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.only(
                    left: 20.w,
                  ),
                  child: Stack(
                    alignment: Alignment.centerLeft,
                    children: [
                      TextFormField(
                        onChanged: (v) {
                          onChanged(v);
                        },
                        controller: _priceController,
                        focusNode: focusNode,
                        cursorColor: ColorConf.yellow,
                        textAlignVertical: TextAlignVertical.center,
                        keyboardType: TextInputType.number,
                        showCursor: true,
                        autofocus: true,
                        //显示光标
                        // readOnly: true, // 禁用唤起系统键盘
                        inputFormatters: [
                          XNumberTextInputFormatter(
                            isAllowDecimal: false,
                            maxIntegerLength: 9,
                          ),
                        ],
                        style: TextStyle(
                          fontSize: 18.sp,
                          color: ColorConf.black,
                          fontWeight: FontWeight.w500,
                        ),
                        decoration: InputDecoration(
                          suffixIcon: _priceController.text.isEmpty
                              ? null
                              : IconButton(
                                  onPressed: () {
                                    _priceController.clear();
                                    onChanged(_priceController.text);
                                  },
                                  icon: Image(
                                    image: AssetImage(
                                        "images/lt_user/circle_clear.png"),
                                    width: 16.w,
                                    height: 16.w,
                                  )),
                          prefixIcon: Container(
                            padding: EdgeInsets.symmetric(horizontal: 5.0.w),
                            child: Text(
                              '¥',
                              style: TextStyle(
                                color: ColorConf.black,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                          ),
                          contentPadding: EdgeInsets.zero,
                          prefixIconConstraints: BoxConstraints(
                            maxHeight: 68.w,
                          ),
                          hintText: "请输入整数金额 ",
                          labelStyle: new TextStyle(
                            color: const Color(0xFFCCCCCC),
                          ),
                          isCollapsed: true,
                          border: InputBorder.none,
                          hintStyle: TextStyle(
                            color: ColorConf.highlightGray,
                            fontSize: 16.sp,
                          ),
                        ),
                      ),
                      if ((double.tryParse(_priceController.text) ?? 0) >= 100)
                        Positioned(
                          left: (20.w + _priceController.text.length * 14.sp),
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 4.w,
                              vertical: 2.w,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              money_tips,
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: rgba(102, 102, 102, 1),
                              ),
                            ),
                          ),
                        )
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
          width: Get.width,
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          padding: EdgeInsets.only(
            bottom: 20.w,
          ),
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Container(
                margin: EdgeInsets.only(
                  left: 12.w,
                  top: 18.w,
                  right: 12.w,
                ),
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        child: Text(
                          "${current_price > 0 ? "请重新出价" : "出个价"}",
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: rgba(51, 51, 51, 1),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        alignment: Alignment.center,
                      ),
                      buildContent(),
                      if (!(user['is_vip'] ?? false))
                        Container(
                          margin: EdgeInsets.symmetric(
                            vertical: 10.w,
                          ),
                          alignment: Alignment.centerLeft,
                          child: available_guarantee <
                                  ConfigProviderUtil.max_deductible_amount
                              ? Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Text(
                                          '当前可出价额度',
                                          style: TextStyle(
                                            color: rgba(153, 153, 153, 1),
                                            fontSize: 12.sp,
                                          ),
                                        ),
                                        Text(
                                          '$tender_price',
                                          style: TextStyle(
                                            color: rgba(51, 51, 51, 1),
                                            fontSize: 12.sp,
                                          ),
                                        ),
                                      ],
                                    ),
                                    SizedBox(
                                      width: 12.w,
                                    ),
                                    GestureDetector(
                                      child: Row(
                                        children: [
                                          Text(
                                            '追加保证金 ',
                                            style: TextStyle(
                                              color: rgba(153, 153, 153, 1),
                                              fontSize: 12.sp,
                                            ),
                                          ),
                                          Image(
                                            image: AssetImage(
                                              'images/lt_common/right_arrow.png',
                                            ),
                                            color: rgba(153, 153, 153, 1),
                                            width: 4.w,
                                          ),
                                        ],
                                      ),
                                      onTap: () {},
                                      behavior: HitTestBehavior.opaque,
                                    )
                                  ],
                                )
                              : GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    DialogUtil.showMyDialog(
                                      dialogType: DialogType.bid_infinite_price,
                                    );
                                  },
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text(
                                        '最高可出价不限额度',
                                        style: TextStyle(
                                          color: Color(0xFF999999),
                                          fontSize: 12.sp,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 4.w,
                                      ),
                                      Image.asset(
                                        "images/ic_order_doubt_lt.png",
                                        width: 12.w,
                                        height: 12.w,
                                      ),
                                    ],
                                  ),
                                ),
                        ),
                      Container(
                        color: ColorConf.white,
                        margin: EdgeInsets.only(
                          top: 40.w,
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            buildCheckItem(),
                            SizedBox(
                              height: 10.w,
                            ),
                            Container(
                              width: double.infinity,
                              child: ButtonWidget(
                                enabled: !visible,
                                type: ButtonType.bgOrange,
                                onPressed: () {
                                  onChanged(_priceController.text);
                                  if (!isAgree) {
                                    ToastUtil.show('请勾选买家须知');
                                    return;
                                  }
                                  if (!visible) {
                                    FocusScope.of(context).unfocus();
                                    if (isLive) {
                                      StatisticsUtil.event(
                                        BiddingLiveEvent.submit_offer,
                                        getUMengMap(
                                          {
                                            "submit_price": _priceController
                                                .text
                                                .toString(),
                                            "backflow_id":
                                                widget.backflowId.toString(),
                                          },
                                        ),
                                      );
                                    } else {
                                      StatisticsUtil.event(
                                        BiddingEvent.submit_offer,
                                        getUMengMap(
                                          {
                                            "submit_price": _priceController
                                                .text
                                                .toString(),
                                            "backflow_id":
                                                widget.backflowId.toString(),
                                          },
                                        ),
                                      );
                                    }
                                    showTips(context);
                                  } else {
                                    ToastUtil.show(visibleStr);
                                  }
                                },
                                child: Text(
                                  '确定出价 ${_priceController.text.isEmpty ? "" : "¥${getMoneyStyleStr(double.parse(_priceController.text).toInt().toString())}"}',
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                    color: ColorConf.white,
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              if (visible)
                Positioned(
                  child: Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          RoucesUtil.getAssets('user/real_name_warning'),
                          color: rgba(224, 32, 32, 1),
                          width: 14.w,
                          height: 14.w,
                        ),
                        SizedBox(
                          width: 5.w,
                        ),
                        Text(
                          "$visibleStr",
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: rgba(224, 32, 32, 1),
                          ),
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                      color: rgba(255, 217, 217, 1),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(15.w),
                        topRight: Radius.circular(15.w),
                      ),
                    ),
                    width: Get.width,
                    height: 24.w,
                  ),
                  top: -20,
                ),
              Positioned(
                child: GestureDetector(
                  child: Container(
                    child: Image.asset(
                      RoucesUtil.getAssets('ic_close_gray'),
                      width: 14.w,
                      height: 14.w,
                      color: rgba(153, 153, 153, 1),
                    ),
                  ),
                  onTap: () {
                    Get.back();
                  },
                ),
                right: 14.w,
                top: 14.w,
              ),
            ],
          )),
      onTap: () {
        FocusScope.of(context).unfocus();
      },
    );
  }
}
